/*
 * @features: 挂在在场景里
 * @description: 说明
 * @Date: 2021-09-30 22:46:52
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-10-27 23:14:15
 * @LastEditors: judu233
 */
import { DEBUG } from "cc/env";
import c3d from "../tool/cc";
import { HotUpdate } from "../Asset/hotupdate/Hotupdate";
import DownloadLoading from "../../com/script/ui/DownloadLoading";
import { Config, ViewZOrder } from "../config/Config";
import { DebugView } from "../../com/script/debug/DebugView";

const { ccclass, property } = c3d._decorator;
export enum UIID {
    UILoading = 0,
    Window = 1,
    UILoading_Prompt = 2,
    Demo = 3,
}


@ccclass('Root')
export class Root extends c3d.Component {
    @property({
        type: Node,
        tooltip: "游戏层"
    })
    game: c3d.Node | null = null;

    debugView: c3d.Node | null = null!;

    comEvent = new Map([
        [HotUpdate.Event.DOWNLOAD_MESSAGE, this.hotUpdate.bind(this)], //加载时注册热更新事件
    ]);

    onLoad() {
        this.init();
    }

    start() {
        if (DEBUG)
            c3d.setDisplayStats(true);
    }

    update() {
        //Service 网络调试
        // engine.serviceManager.update();

        //远程资源下载任务调度
        GM.assetMgr.update();
    }

    onDestroy() {
        GM.uiMgr.adaptor.onDestroy();
        // engine.serviceManager.onDestroy();
        //入口管理器
        GM.entryMgr.onDestroy(this.node);
    }

    init() {
        //判断是否开启调试
        let debug = c3d.find("debug", this.node);
        this.debugView = c3d.find("debugView", this.node);
        if (debug && this.debugView) {
            if (Config.isShowDebugButton) {
                debug.active = true;
                this.debugView.active = false;
                //添加调试视图脚本
                let view = this.debugView.addComponent(DebugView)
                if (view) view.debug = debug;
                debug.on(c3d.SystemEvent.EventType.TOUCH_END, () => {
                    if (debug) debug.active = false;
                    if (this.debugView) {
                        this.debugView.active = true;
                    }
                });
            } else {
                debug.destroy();
                this.debugView.destroy();
            }
        }

        //初始化
        GM.init(this);
    }

    /**
     * 热更新
     * @param data 更新数据
     */
    hotUpdate(data: HotUpdate.MessageData) {
        if (data.isOk) {
            GM.uiMgr.open({ type: DownloadLoading, zIndex: ViewZOrder.Loading, args: [data.state, data.name, data.bundle] });
        } else {
            c3d.game.end();
        }
    }

}
